import { formatDateByNow } from '~/utils/util.date';
import { nameDescVerify } from '~/server/validation';
import { SubCategoryModel } from '~/server/models/sub_category.model';

/**
 * @api {patch} /admin/category/update_sub 更新二级分类
 * @apiName 更新二级分类
 * @apiGroup 分类管理
 * @apiDescription 更新二级分类
 *
 * @apiPermission admin、resource
 *
 * @apiSampleRequest /admin/category/update_sub
 *
 * @apiHeader {String} Authorization 用户 Token
 *
 * @apiBody {String} id 分类 ID
 * @apiBody {String} name 分类名称
 * @apiBody {String} description 分类描述
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '更新成功',
 * }
 */
export default defineEventHandler(async (event) => {
	const checkPermission = checkAdminUserPermission(event, ['admin', 'resource']);
	if (!checkPermission) {
		return {
			code: 0,
			message: '无权访问',
		};
	}

	try {
		const { id, name, description } = await readBody(event);

		// 参数校验
		const validation = nameDescVerify.validate({ name, description }).error?.message;
		if (validation && validation !== void 0) {
			return {
				code: 0,
				message: validation,
			};
		}

		// 更新分类
		const updateResult = await SubCategoryModel.findByIdAndUpdate(id, {
			$set: { name, description, updatedAt: formatDateByNow() },
		});

		if (updateResult === null) {
			return {
				code: 0,
				message: '分类不存在',
			};
		}

		return {
			code: 1,
			message: '更新成功',
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
